package com.wyz.calibur.infrastructure.config.security;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.wyz.calibur.constant.SecurityConstant;
import com.wyz.calibur.enums.RedisKeyEnum;
import com.wyz.calibur.enums.ResultCode;
import com.wyz.calibur.infrastructure.utils.AuthenticationUtil;
import com.wyz.calibur.infrastructure.utils.RedisUtil;
import com.wyz.calibur.result.Result;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description: 登录成功处理类
 * @Author: wei yz
 * @Date: 2022/6/20 16:16
 */
public class CliburAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    private static final Logger log = LoggerFactory.getLogger(CliburAuthenticationSuccessHandler.class);

    @Autowired
    private AuthenticationUtil authenticationUtil;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        log.info("===========登录成功===========");
        // 存到redis的用户信息
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        // 验证是否已经登录过,如果已经登录过的用户则清除之前的登录信息并重新生成
        String voucherKey = RedisKeyEnum.LOGIN_VOUCHER.getKey() + SecureUtil.md5(userDetails.getUsername());
        String clientKey = (String) redisUtil.get(voucherKey);
        // 存在clientKey则表示存在该用户
        if (StringUtils.isNotBlank(clientKey) && StringUtils.isNotBlank((String) redisUtil.get(RedisKeyEnum.AUTH_TOKEN.getKey() + clientKey))) {
            // 存在则jwt认证信息则删除
            authenticationUtil.delTokenInfo(clientKey, voucherKey);
        }
        String tokenKey = authenticationUtil.getFrontToken(userDetails);
        response.setHeader(SecurityConstant.TOKEN, tokenKey);
        response.setContentType(SecurityConstant.CONTENT_TYPE);
        response.getWriter().println(
                JSON.toJSONString(new Result()
                        .setSuccess(true)
                        .setCode(ResultCode.SUCCESS)
                        .setData(tokenKey)
                        .setMessage(ResultCode.SUCCESS.getDesc())));
    }

}
